package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import commands.FilesInUserFolderNameCommand;
import commands.GetUserCommand;
import commands.UserDropBoxFilesCommand;
import commands.UserDropBoxFoldersCommand;

import database.DbFile;
import database.DbFolder;
import database.User;


/**
 * UserDropboxServlet implementation class ServerServlet - show the content of the dropbox.
 * urls: .../UserDropboxServlet + .../UserDropboxServlet/folder/*
 */
public class UserDropboxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	UserDropBoxFoldersCommand userDropBoxFolders;
	UserDropBoxFilesCommand userDropBoxFiles;
	FilesInUserFolderNameCommand filesInUserFolderName;
	GetUserCommand getUserCommand;
       
       
    /**
     * constructor
     * @see HttpServlet#HttpServlet()
     */
    public UserDropboxServlet() {
        super();
        // TODO Auto-generated constructor stub
        userDropBoxFolders = new UserDropBoxFoldersCommand();
        userDropBoxFiles = new UserDropBoxFilesCommand();
        filesInUserFolderName = new FilesInUserFolderNameCommand();
        getUserCommand = new GetUserCommand();
        
    }

	/**
	 * urls: /UserDropboxServlet - return the user dropbox with its folders and files
	 * 		/UserDropboxServlet/folder/folderName - return the files that in the user folder
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setStatus(HttpServletResponse.SC_OK);
        
        PrintWriter out = response.getWriter();
        
        String userID = (String) request.getSession().getAttribute("userID");
        String password = (String) request.getSession().getAttribute("password");
        String folderName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
        
        System.out.println("timeout " + request.getSession().getMaxInactiveInterval());
        
        //if the folder is the dropbox folder..
        if (!request.getRequestURI().contains("folder"))
        {
        	userDropboxHome(userID, password, out);
        	out.close();
        	return;
        }
        
        //get the files that under this folder
        List<DbFile> listFiles = filesInUserFolderName.action(userID, folderName);
              
        out.println("<html>");
        out.println("<head>");
        out.println("<title> clever dropbox =) </title>");
        out.println("</head>");
        out.println("<body bgcolor=#66CCFF>");
        
        //for share this folder
        out.println("<br><h3 align='center'> for sharing this folder with another user, please enter his user name and click the button </h3>");
        out.println("<h3 align='center'> <form action='/SharedFolderServlet/" + folderName + "' method='POST'>   " +
    			"<input type='text' name='userSharedID' size='20'>" +
    			"<input type='submit' value='Shared'> </form> </h3> <BR> <BR>");
        
        //for upload a file
        out.println("<h3 align='center'> for upload a file, please select it and click the button"+
        		"<form action='/UploadServlet/folder/" + folderName +"' enctype='multipart/form-data' method='POST'>"+
        		"<input type='file' name='file'> <br><br>" + 
        		"<input type='Submit' value='Upload File'><br> </form> </h3><br><br>");
        
                
        if (listFiles!=null)
        {
        	
	        Iterator<DbFile> iteratorFiles = listFiles.iterator();
	        DbFile file;
	    
	        //if there are no files
	        if (!iteratorFiles.hasNext())
	        {
	        	out.println("<h3 align='center'> there are no files in this folder. <BR> </h3>" );
	        }
	        else
	        {
	        	//print the files
		        out.println("<h3 align='center'> files in this folder: <BR>" );
		        while (iteratorFiles.hasNext())
		        {
		        	file = iteratorFiles.next();
		        	//a link for dowmload the file
		        	out.println("<a href='/DownloadServlet/"+ file.getFileID() + "/" +file.getFileName()+"'>");
		        	out.println(file.getFileName() + "</a> <br>");
		        }
	        }
	        
        }
        
        out.println("</h3> <BR> <BR> <a href='/UserDropboxServlet'> <h4 align='center'> to return to your dropbox - click here... </h4> </a>");
        
        out.println("</body>");
        out.println("</html>");
        
        out.close();      
                   
        
	}

	/**
	 * urls: /UserDropboxServlet - return the user dropbox with its folders and files
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String userID = request.getParameter("userID").toString(); 
        String password = request.getParameter("password").toString();
        
        request.getSession().setAttribute("userID" ,userID);
        request.getSession().setAttribute("password" ,password);
        
        userDropboxHome(userID,password,out);

        out.close();

	}
	
	//print to the outputStream the user dropbox home
	private void userDropboxHome(String userID, String password, PrintWriter out)
	{
		User user = getUserCommand.action(userID);
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title> clever dropbox =) </title>");
        out.println("</head>");
        out.println("<body bgcolor=#66CCFF>");
        
        //if there is no such user
        if (user==null)
        {
        	out.println("<br> <br> <h3 align='center'> user does not exist </h3> <BR>");
        	out.println(" <a href='/registry'> <h4 align='center'> to register - click here... </h4> </a> <BR>");
        	out.println(" <a href='/'> <h4 align='center'> to return to sign in page - click here... </h4> </a>");
        }
        //if the password is wrong
        else if (!user.getPassword().equals(password))
        {
        	out.println("<br> <br> <h3 align='center'> wrong password </h3> <BR>");
        	out.println("<a href='/'> <h4 align='center'> to try again - click here... </h4></a> <BR>");  
        	out.println("<a href='/registry'> <h4 align='center'> to register - click here... </h4> </a>");
        }
        else
        {
        	//all right - show the user folders and files
	        List<DbFolder> listFolders = userDropBoxFolders.action(userID);
	        List<DbFile> listFiles = userDropBoxFiles.action(userID);
	        
	        //the folders
	        Iterator<DbFolder> iteratorFolders = listFolders.iterator();
	        DbFolder folder;
	        
	        //the files
	        Iterator<DbFile> iteratorFiles = listFiles.iterator();
	        DbFile file;
	        	     
	        	        
	        out.println("<h2 align='center'> Welcom to your Dropbox! =) </h2> <br>");
	        
	        //upload a file to the dropbox
	        out.println("<h3 align='center'> for upload a file, please select it and click the button"+
	        		"<form action='/UploadServlet' enctype='multipart/form-data' method='POST'>"+
	        		"<input type='file' name='file'> <br><br>" + 
	        		"<input type='Submit' value='Upload File'><br> </form> </h3><br><br>");
	        
	        //if there are no folders/files
	        if ((!iteratorFolders.hasNext()) && (!iteratorFiles.hasNext()))
	        {
	        	out.println("<br> <br> <h3 align='center'> your dropbox is empty.. </h3>");
	        }
	        else
	        {
	        	
	        	out.println("<h3 align='center'> your dropbox folders and files: <BR><BR>");
	        	
	        	//check if there are folders
	        	if (iteratorFolders.hasNext())
	        		out.println("folders: <BR>");
	        	else
	        		out.println("folders: no folders.  <BR>");
	        	
	        	//print the user folders
		        while (iteratorFolders.hasNext())
		        {
		        	folder = iteratorFolders.next();
		        	//add a link to to the folder content
		        	out.println("<a href='/UserDropboxServlet/folder/" +folder.getFolderName() + "'>" + folder.getFolderName() + "</a>" + "<br>");
		        }
		        
		        out.println("<BR>");
		        
		        //check if there are files
		        if (iteratorFiles.hasNext())
	        		out.println("files: <BR>");
	        	else
	        		out.println("files: no files.  <BR>");
		        
		        //print the user files
		        while (iteratorFiles.hasNext())
		        {
		        	file = iteratorFiles.next();
		        	//add a link for download the file
		        	out.println("<a href='/DownloadServlet/"+ file.getFileID() + "/" +file.getFileName()+"'>");
		        	out.println(file.getFileName() + "</a> <br>");
		        }    
		        
	        }
	        
	        out.println("</h3> <BR> <BR> <a href='/'> <h4 align='center'> to return to sign in page - click here... </h4> </a>");
        }
                
       
        out.println("</body>");
        out.println("</html>");
		
	}

}
